package kk.controller;

import com.github.pagehelper.PageInfo;
import kk.domain.Traveller;
import kk.service.TravellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RequestMapping("/traveller")
@Controller
public class TravellerController {

    @Autowired
    private TravellerService travellerService;

    @RequestMapping("/findAll")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public ModelAndView findAll(Integer pageNum,Integer pageSize){
        List<Traveller> travellerList = travellerService.findAll(pageNum, pageSize);
        PageInfo pageInfo=new PageInfo(travellerList);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.setViewName("traveller-list");
        return modelAndView;
    }

    @RequestMapping("/save")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public String save(Traveller traveller){
        travellerService.add(traveller);
        return "redirect:/traveller/findAll?pageNum=1&pageSize=4";
    }

    @RequestMapping("/findById")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public ModelAndView findById(Integer id){
        Traveller traveller = travellerService.findById(id);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("traveller",traveller);
        modelAndView.setViewName("traveller-edit");
        return modelAndView;
    }

    @RequestMapping("/update")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public String update(Traveller traveller){
        travellerService.update(traveller);
        return "redirect:/traveller/findAll?pageNum=1&pageSize=4";
    }

    @RequestMapping("/findByName")
    @PreAuthorize("hasAnyRole('ROLE_USER','ROLE_ADMIN')")
    public ModelAndView findByName(String name,Integer pageNum,Integer pageSize){
        String newName="%"+name+"%";
        List<Traveller> travellerList = travellerService.findByName(newName, pageNum, pageSize);
        PageInfo pageInfo=new PageInfo(travellerList);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("pageInfo",pageInfo);
        modelAndView.addObject("name",name);
        modelAndView.setViewName("traveller-list");
        return modelAndView;
    }
}
